<?php
/**
 * OAuthHandlerForQQ class file.
 *
 * @author Zhang Jinlong <466028373@qq.com>
 * @link http://www.ijianzhi.cn
 * @copyright Copyright &copy; 2013 DianJin Soft
 */

class OAuthHandlerForQQ
{
    /**
     * 构造函数
     */
    public function __construct()
    {
    }

    /**
     * 跳转至QQ登录界面
     */
    public function login()
    {
        Yii::app()->session['qq_oauth_state'] = Helper::generateOAuthState();

        $queryData = array(
            'response_type' => 'code',
            'client_id' => Yii::app()->params['oauth']['qq']['appId'],
            'redirect_uri' => Yii::app()->params['oauth']['qq']['callback'],
            'state' => Yii::app()->session['qq_oauth_state'],
            'scope' => Yii::app()->params['oauth']['qq']['scope']
        );

        $loginUrl = Yii::app()->params['oauth']['qq']['getAuthCodeUrl'].'?'.http_build_query($queryData);

        Helper::showMessage(NULL, $loginUrl, 0);
    }

    /**
     * QQ CONNECT 回调地址
     * @throws OAuthException
     * @return Ambigous <string>
     */
    public function callback()
    {
        if (Yii::app()->request->getQuery('state') !== Yii::app()->session['qq_oauth_state'])
        {
            throw new OAuthException('The validate for qq oauth state fail.');
        }

        $queryData = array(
            'grant_type' => 'authorization_code',
            'client_id' => Yii::app()->params['oauth']['qq']['appId'],
            'redirect_uri' => Yii::app()->params['oauth']['qq']['callback'],
            'client_secret' => Yii::app()->params['oauth']['qq']['appKey'],
            'code' => Yii::app()->request->getQuery('code'),
        );

        $tokenUrl = Yii::app()->params['oauth']['qq']['getAccessTokenUrl'].'?'.http_build_query($queryData);
        $response = WebHelper::get($tokenUrl);

        if (strpos($response, 'callback') !== FALSE)
        {
            $leftPos = strpos($response, '(');
            $rightPos = strrpos($response, ')');
            $response  = substr($response, $leftPos + 1, $rightPos - $leftPos -1);
            $message = json_decode($response);

            if (isset($msg->error))
            {
                throw new OAuthException('Get access token from qq server fail, with message: '.$message->error_description, $message->error);
            }
        }

        $params = array();
        parse_str($response, $params);

        Yii::app()->session['qq_access_token'] = $params['access_token'];

        return $params['access_token'];
    }

    /**
     * 获得OPEN-ID
     * @throws OAuthException
     * @return string
     */
    public function getOpenId()
    {
        $queryData = array(
            'access_token' => Yii::app()->session['qq_access_token'],
        );

        $graphUrl = Yii::app()->params['oauth']['qq']['getOpenIdUrl'].'?'.http_build_query($queryData);
        $response = WebHelper::get($graphUrl);

        if (strpos($response, 'callback') !== FALSE)
        {
            $leftPos = strpos($response, '(');
            $rightPos = strrpos($response, ')');
            $response  = substr($response, $leftPos + 1, $rightPos - $leftPos -1);
        }

        $message = json_decode($response);

        if (isset($message->error))
        {
            throw new OAuthException('Get open id from qq server fail, with message: '.$message->error_description, $message->error);
        }

        Yii::app()->session['qq_openid'] = $message->openid;

        return $message->openid;
    }
}